﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;

namespace WhatToDoToday
{
    public partial class GamePage : PhoneApplicationPage
    {       
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;

        // For rendering the XAML onto a texture
        UIElementRenderer elementRenderer;

        Texture2D background;
        private TimeSpan timeToNextTap;
        private double timeInterval;

        enum ResponseOptions { Yes, No, Maybe, TryAgain }
        Random random;
        string message;
        SpriteFont messageFont;

        public GamePage()
        {

            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            // Use the LayoutUpdate event to know when the page layout 
            // has completed so that we can create the UIElementRenderer.
            LayoutUpdated += new EventHandler(GamePage_LayoutUpdated);
            
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            // TODO: use this.content to load your game content here
            background = contentManager.Load<Texture2D>("what");
            messageFont = contentManager.Load<SpriteFont>("SpriteFont1");

            timeInterval = .5;
            timeToNextTap = TimeSpan.FromSeconds(timeInterval);
            message = "";

            // Start the timer
            timer.Start();            

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
            TouchCollection touchCollection = TouchPanel.GetState();
            if (touchCollection.Count > 0 && timeToNextTap <= TimeSpan.Zero)
            {
                random = new Random();
                System.Diagnostics.Debug.WriteLine("Clicked");
                int newNumber = random.Next(3);
                if (newNumber == 0)
                {
                    int yesNumber = random.Next(5);

                    if (yesNumber == 0)
                        message = "I'd say you should \ngo outside.";
                    else if (yesNumber == 1)
                        message = "Do whatever you want.";
                    else if (yesNumber == 2)
                        message = "You have something \nto work on? Do it.";
                    else if (yesNumber == 3)
                        message = "Invite a friend to \nlunch.";
                    else
                        message = "Be happy that you \n are alive.";
                }
                else if (newNumber == 1)
                {
                    int nonNumber = random.Next(5);

                    if (nonNumber == 0)
                        message = "Play a video game.";
                    else if (nonNumber == 1)
                        message = "Discuss the meaning\nof life.";
                    else if (nonNumber == 2)
                        message = "Stop wasting time on\n apps.";
                    else if (nonNumber == 3)
                        message = "Make something special.";
                    else
                        message = "Go out for a run.";
                }
                else
                {
                    int noNumber = random.Next(5);

                    if (noNumber == 0)
                        message = "Go back to sleep.";
                    else if (noNumber == 1)
                        message = "Relax.";
                    else if (noNumber == 2)
                        message = "I don't know.";
                    else if (noNumber == 3)
                        message = "Listen to music.";
                    else
                        message = "Clean up the house.";                   
                }

                timeToNextTap = TimeSpan.FromSeconds(timeInterval);
            }

            timeToNextTap -= e.ElapsedTime;
            System.Diagnostics.Debug.WriteLine(timeToNextTap.ToString());
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);

            // Render the Silverlight controls using the UIElementRenderer.
            elementRenderer.Render();

            // Draw the sprite
            spriteBatch.Begin();

            spriteBatch.Draw(background, Vector2.Zero, Color.White);

            // Using the texture from the UIElementRenderer, 
            // draw the Silverlight controls to the screen.
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);

            // Draw the response.
            spriteBatch.DrawString(messageFont, message, new Vector2((SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2) - (messageFont.MeasureString(message).X / 2), 500), Color.White);

            spriteBatch.End();
        }

        void GamePage_LayoutUpdated(object sender, EventArgs e)
        {
            // Create the UIElementRenderer to draw the XAML page to a texture.

            // Check for 0 because when we navigate away the LayoutUpdate event
            // is raised but ActualWidth and ActualHeight will be 0 in that case.
            if ((ActualWidth > 0) && (ActualHeight > 0))
            {
                SharedGraphicsDeviceManager.Current.PreferredBackBufferWidth = (int)ActualWidth;
                SharedGraphicsDeviceManager.Current.PreferredBackBufferHeight = (int)ActualHeight;
            }

            if (null == elementRenderer)
            {
                elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
            }
        }
    }
}